package com.tong.embeddedvr.filter;

import com.tong.embeddedvr.dto.UserOutputDTO;
import com.tong.embeddedvr.entity.UserEntity;
import com.tong.embeddedvr.utils.CommonUtil;
import org.apache.logging.log4j.ThreadContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebFilter(urlPatterns = "/host/*",filterName = "hostFilter")
public class HostFilter implements Filter {

    private final Logger logger = LoggerFactory.getLogger(UserFilter.class);

    private final String EXCLUDED_URL[] = {};

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setHeader("Access-Control-Allow-Credentials", "true");
        //允许对应的源
        response.setHeader("Access-Control-Allow-Origin",request.getHeader("origin"));
        //对session放行
        response.setHeader("Set-Cookie","HttpOnly;Secure;SameSite=None");
        //获得url
        String url = ((HttpServletRequest) servletRequest).getServletPath();
        boolean flag = false;
        //确定是否在被排除的URL中
        for (String s : EXCLUDED_URL) {
            if(url.contains(s)){
                flag = true;
            }
        }
        HttpSession session = ((HttpServletRequest) servletRequest).getSession();
        logger.info("session:[{}]",session.getId());
        if(flag||((UserOutputDTO)session.getAttribute("user")).getUserIsTeacher()==1){
            //取session的前10位作为日志的标记
            ThreadContext.put("logId",session.getId().substring(0,10));
            filterChain.doFilter(request,response);
        }else{
            servletResponse.setContentType("application/json;charset=utf-8");
            PrintWriter writer = servletResponse.getWriter();
            writer.print(CommonUtil.ajaxReturn(400,"无此权限"));
        }
    }

    @Override
    public void destroy() {

    }
}
